<script setup>
import { ref, onMounted } from 'vue'
import api from '@/api/auth'
import { useAuthStore } from '@/stores/auth'
import MenuTree from './MenuTree.vue'

const menuTree = ref([])
const loading = ref(true)
const authStore = useAuthStore()
const activeMenu = ref('')

const fetchMenu = async () => {
  loading.value = true
  try {
    const res = await api.get('/sysMenu/menuTreeByUser')
    if (res && res.code === 0) {
      menuTree.value = res.data
      if (menuTree.value.length > 0) {
        activeMenu.value = menuTree.value[0].url || String(menuTree.value[0].id)
      }
    }
  } catch (e) {
    console.error('菜单获取失败', e)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  fetchMenu()
})
</script>

<template>
  <div class="admin-layout">
    <aside class="sidebar">
      <div class="logo">
        <i class="el-icon-s-home" style="font-size:32px;"></i>
        <span style="margin-left:10px;">大事件</span>
      </div>
      <el-menu
        :default-active="activeMenu"
        class="el-menu-vertical-demo"
        background-color="#18191a"
        text-color="#fff"
        active-text-color="#ffd04b"
        router
        style="border:none;flex:1;"
      >
        <template v-if="loading">
          <el-menu-item disabled>菜单加载中...</el-menu-item>
        </template>
        <template v-else>
          <MenuTree :menus="menuTree" />
        </template>
      </el-menu>
    </aside>
    <main class="main-content">
      <header class="header">
        <span>黑马程序员：{{ authStore.userInfo?.username || '未登录' }}</span>
        <span class="avatar"><svg width="32" height="32" viewBox="0 0 24 24"><circle cx="12" cy="8" r="4" fill="#eee"/><path d="M4 20c0-4 16-4 16 0" fill="#eee"/></svg></span>
      </header>
      <section class="content">
        <router-view />
      </section>
      <footer class="footer">
        大事件 ©2023 Created by 黑马程序员
      </footer>
    </main>
  </div>
</template>

<style scoped>
.admin-layout {
  display: flex;
  height: 100vh;
  background: #f7f8fa;
}
.sidebar {
  width: 220px;
  background: #18191a;
  color: #fff;
  display: flex;
  flex-direction: column;
  align-items: stretch;
}
.logo {
  display: flex;
  align-items: center;
  padding: 24px 16px;
  font-size: 22px;
  font-weight: bold;
  border-bottom: 1px solid #222;
}
.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}
.header {
  height: 56px;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 32px;
  border-bottom: 1px solid #eee;
}
.avatar {
  margin-left: 24px;
  font-size: 24px;
}
.content {
  flex: 1;
  padding: 32px;
  background: #fff;
  margin: 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px #0001;
}
.footer {
  text-align: center;
  color: #888;
  padding: 16px 0;
  font-size: 14px;
}
</style> 